package com.example.administrator.studyframedemo.utils;

import com.example.administrator.studyframedemo.retorfit_and_rxJava.CaiPu;
import com.example.administrator.studyframedemo.retorfit_and_rxJava.CaipuApi;

import java.util.HashMap;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.schedulers.Schedulers;

public class RxJavaRetorfitUtils {
    private static RxJavaRetorfitUtils utils=new RxJavaRetorfitUtils();
    CaipuApi caipuApi;
    public RxJavaRetorfitUtils(){
        OkHttpClient client=new OkHttpClient.Builder().connectTimeout(5, TimeUnit.SECONDS)
                .build();
        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl("http://www.kuaidi100.com/")
                .client(client)
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        caipuApi = retrofit.create(CaipuApi.class);
    }

    public static RxJavaRetorfitUtils getInstens(){
        return utils;
    }

    //提供的方法让使用者去调用
    public void getCaiPu(HashMap map, final CallBack call){
        Observable<CaiPu> caipu=caipuApi.getCaiPu(map);
        //调度线程
        caipu.subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Action1<CaiPu>() {
                    @Override
                    public void call(CaiPu caiPu) {
                        //可以在里面进行操作
                        if(null==caiPu){
                            call.onError();
                        }else{
                            call.onSuccess(caiPu);
                        }
                    }
                });
    }
    //这是一个回调借口
    public interface CallBack{
        void onSuccess(CaiPu caiPu);
        void onError();
    }
}